package com.szy.news.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import cn.sharesdk.framework.ShareSDK;

import com.szy.news.control.MyApplication;
import com.szy.news.custom.Category;
import com.szy.news.custom.CustomSimpleAdapter;
import com.szy.news.service.SyncHttp;
import com.szy.news.util.DensityUtil;
import com.szy.news.util.StringUtil;
import com.szy.news.util.URL;

public class MainActivity extends Activity {
	private final int COLUMNWIDTHPX = 215;
	private final int FLINGVELOCITYPX = 800; // 滚动距离
	private final int NEWSCOUNT = 7; // 返回新闻数目
	private final int SUCCESS = 0;// 加载成功
	private final int NONEWS = 1;// 该栏目下没有新闻
	private final int NOMORENEWS = 2;// 该栏目下没有更多新闻
	private final int LOADERROR = 3;// 加载失败

	private int mColumnWidthDip;
	private int mFlingVelocityDip;
	private int mCid;
	private String mCatName;
	private ArrayList<HashMap<String, Object>> mNewsData;
	private ListView mNewsList;
	private SimpleAdapter mNewsListAdapter;
	private LayoutInflater mInflater;
	private Button mTitlebarRefresh;
	private ProgressBar mLoadnewsProgress;
	private Button mLoadMoreBtn;
	private Button btn_user;
	private SharedPreferences sp;
	private MyApplication my,my1;
	private LoadNewsAsyncTask loadNewsAsyncTask;
//	private ImageView im1;
//	private FinalBitmap bitmap_1;
//	String path = "http://"+URL.path+":8080/web/"; 
	
	//图片广告流的定义
    private int[] imgResIDs = new int[]
    { R.drawable.image1_1_0, R.drawable.image1_2_0, R.drawable.image3_1_0, R.drawable.image2_1_0, R.drawable.image2_2_0 };
    private int[] radioButtonID = new int[]
    { R.id.radio0, R.id.radio1, R.id.radio2, R.id.radio3, R.id.radio4 };
    private ViewPager pager;
    private RadioGroup mGroup;
    private ArrayList<View> items = new ArrayList<View>();
    private int mCurrentItem = 0;
    private int mItem;
    private Runnable mPagerAction;
    private boolean isFrist = true;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ShareSDK.initSDK(this);
		setContentView(R.layout.main);
		my=(MyApplication) this.getApplication();
		
		mInflater = getLayoutInflater();
		mNewsData = new ArrayList<HashMap<String, Object>>();
		mNewsList = (ListView) findViewById(R.id.newslist);
		mTitlebarRefresh = (Button) findViewById(R.id.titlebar_refresh);
		mLoadnewsProgress = (ProgressBar) findViewById(R.id.loadnews_progress);
		mTitlebarRefresh.setOnClickListener(loadMoreListener);
		btn_user = (Button) findViewById(R.id.btn_user);
		sp = getSharedPreferences("userdata", 0);
		
		pager = (ViewPager) findViewById(R.id.tuijian_pager1);
        mGroup = (RadioGroup) findViewById(R.id.radioGroup1);
		
//		bitmap_1=FinalBitmap.create(this);
//		im1 = (ImageView) findViewById(R.id.bitmap1);
//		bitmap_1.display(im1, path+"b.jpg");
//		im1.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				
//				Intent intent = new Intent(MainActivity.this,Image1Activity.class);
//				intent.putExtra("mNid", "1");
//				startActivity(intent);
//				
//			}
//		});
		
		btn_user.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(MainActivity.this, SetActivity.class);
//				intent.setClass(MainActivity.this, SetActivity.class);
				startActivity(intent);
			}
		});

		// 把px转换成dip
		mColumnWidthDip = DensityUtil.px2dip(this, COLUMNWIDTHPX);
		mFlingVelocityDip = DensityUtil.px2dip(this, FLINGVELOCITYPX);

		// 获取新闻分类
		String[] categoryArray = getResources().getStringArray(
				R.array.categories);
		// 把新闻分类保存到List中
		final List<HashMap<String, Category>> categories = new ArrayList<HashMap<String, Category>>();
		// 分割新闻类型字符串
		for (int i = 0; i < categoryArray.length; i++) {
			String[] temp = categoryArray[i].split("[|]");
			if (temp.length == 2) {
				int cid = StringUtil.String2Int(temp[0]);
				String title = temp[1];
				Category type = new Category(cid, title);
				HashMap<String, Category> hashMap = new HashMap<String, Category>();
				hashMap.put("category_title", type);
				categories.add(hashMap);
			}
		}
		// 默认选中的新闻分类
		mCid = 1;
		mCatName = "国内";
		// 创建Adapter，指明映射字段
		CustomSimpleAdapter categoryAdapter = new CustomSimpleAdapter(this,
				categories, R.layout.category_title,
				new String[] { "category_title" },
				new int[] { R.id.category_title });

		GridView category = new GridView(this);
		category.setColumnWidth(mColumnWidthDip);// 每个单元格宽度
		category.setNumColumns(GridView.AUTO_FIT);// 单元格数目
		category.setGravity(Gravity.CENTER);// 设置对其方式
		// 设置单元格选择是背景色为透明，这样选择时就不显示黄色背景
		category.setSelector(new ColorDrawable(Color.TRANSPARENT));
		// 根据单元格宽度和数目计算总宽度
		int width = mColumnWidthDip * categories.size();
		LayoutParams params = new LayoutParams(width, LayoutParams.FILL_PARENT);
		// 更新category宽度和高度，这样category在一行显示
		category.setLayoutParams(params);
		// 设置适配器
		category.setAdapter(categoryAdapter);
		// 把category加入到容器中
		LinearLayout categoryList = (LinearLayout) findViewById(R.id.category_layout);
		categoryList.addView(category);
		// 添加单元格点击事件
		category.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
//				mNewsListAdapter.notifyDataSetChanged();
				TextView categoryTitle;
				// 恢复每个单元格背景色
				for (int i = 0; i < parent.getChildCount(); i++) {
					categoryTitle = (TextView) (parent.getChildAt(i));
					categoryTitle.setBackgroundDrawable(null);
					categoryTitle.setTextColor(0XFFADB2AD);
				}
				// 设置选择单元格的背景色
				categoryTitle = (TextView) (parent.getChildAt(position));
				categoryTitle
						.setBackgroundResource(R.drawable.categorybar_item_background);
				categoryTitle.setTextColor(0XFFFFFFFF);
				// 获取选中的新闻分类id
				mCid = categories.get(position).get("category_title").getCid();
				mCatName = categories.get(position).get("category_title")
						.getTitle();
				// 获取该栏目下新闻
				// getSpeCateNews(mCid,mNewsData,0,true);
				// 通知ListView进行更新
				//mNewsListAdapter.notifyDataSetChanged();
				loadNewsAsyncTask = new LoadNewsAsyncTask();
				loadNewsAsyncTask.execute(mCid, 0, true);
			}
		});

		// 箭头
		final HorizontalScrollView categoryScrollview = (HorizontalScrollView) findViewById(R.id.category_scrollview);
		Button categoryArrowRight = (Button) findViewById(R.id.category_arrow_right);
		categoryArrowRight.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				categoryScrollview.fling(DensityUtil.px2dip(MainActivity.this,
						mFlingVelocityDip));
			}
		});
		// 获取指定栏目的新闻列表
		// getSpeCateNews(mCid,mNewsData,0,true);
//		mNewsListAdapter.notifyDataSetChanged();
		mNewsListAdapter = new SimpleAdapter(this, mNewsData,
				R.layout.newslist_item, new String[] { "newslist_item_title",
						"newslist_item_digest", "newslist_item_source",
						"newslist_item_ptime" }, new int[] {
						R.id.newslist_item_title, R.id.newslist_item_digest,
						R.id.newslist_item_source, R.id.newslist_item_ptime });
		View loadMoreLayout = mInflater.inflate(R.layout.loadmore, null);
		mNewsList.addFooterView(loadMoreLayout);
		//1/6
		mNewsList.setAdapter(mNewsListAdapter);
		
		mNewsListAdapter.notifyDataSetChanged();
		
		mNewsList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent(MainActivity.this,
						NewsDetailsActivity.class);
				// 把需要的信息放到Intent中
				intent.putExtra("newsDate", mNewsData);
				intent.putExtra("position", position);
				intent.putExtra("categoryName", mCatName);
				startActivity(intent);
				
				//更新数据
				mNewsListAdapter.notifyDataSetChanged();
			}
		});

		mLoadMoreBtn = (Button) findViewById(R.id.loadmore_btn);
		mLoadMoreBtn.setOnClickListener(loadMoreListener);

		loadNewsAsyncTask = new LoadNewsAsyncTask();
		loadNewsAsyncTask.execute(mCid, 0, true);
		/**
		 * 网络状态判断
		 * 
		 * */
		ConnectivityManager manger = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manger.getActiveNetworkInfo();
		if (info != null && info.isConnected()) {
//			Toast.makeText(MainActivity.this, "网络状态良好", Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(MainActivity.this, "当前无网络访问", Toast.LENGTH_SHORT)
					.show();
			AlertDialog.Builder dialog = new AlertDialog.Builder(
					MainActivity.this);
			dialog.setTitle("请检查网络状态");
			dialog.setNegativeButton("确定",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							if (android.os.Build.VERSION.SDK_INT > 10) {
								// 3.0以上打开设置界面，也可以直接用ACTION_WIRELESS_SETTINGS打开到wifi界面
								Log.d("ok1", "success");
								startActivity(new Intent(
										android.provider.Settings.ACTION_SETTINGS));
							} else {
								Log.d("ok2", "success");
								startActivity(new Intent(
										android.provider.Settings.ACTION_WIRELESS_SETTINGS));
							}
						}
					});
			dialog.setPositiveButton("取消",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
			dialog.show();

		}

//		  pager = (ViewPager) findViewById(R.id.tuijian_pager);
//	        mGroup = (RadioGroup) findViewById(R.id.radioGroup1);
	        initAllItems();
	        pager.setAdapter(new PagerAdapter()
	        {
	            // 创建
	            @Override
	            public Object instantiateItem(View container, int position)
	            {
	                View layout = items.get(position % items.size());
	                pager.addView(layout);
	                return layout;
	            }
	            
	            // 销毁
	            @Override
	            public void destroyItem(View container, int position, Object object)
	            {
	                View layout = items.get(position % items.size());
	                pager.removeView(layout);
	            }
	            
	            @Override
	            public boolean isViewFromObject(View arg0, Object arg1)
	            {
	                return arg0 == arg1;
	                
	            }
	            
	            @Override
	            public int getCount()
	            {
	                return imgResIDs.length;
	            }
	            
	        });
	        pager.setOnPageChangeListener(new OnPageChangeListener()
	        {
	            
	            @Override
	            public void onPageSelected(final int arg0)
	            {
	                mCurrentItem = arg0 % items.size();
	                pager.setCurrentItem(mCurrentItem);
	                mGroup.check(radioButtonID[mCurrentItem]);
	                items.get(arg0).findViewById(R.id.tuijian_header_img).setOnClickListener(new OnClickListener()
	                {
	                    @Override
	                    public void onClick(View v)
	                    {	
	                    	Intent in = new Intent(MainActivity.this,PhotoActivity.class);
	                    	startActivity(in);
//	                        Toast.makeText(MyViewPagerActivity.this, arg0 + "", 1000).show();
	                    }
	                });
	            }
	            
	            @Override
	            public void onPageScrolled(int arg0, float arg1, int arg2)
	            {
	                // TODO Auto-generated method stub
	            }
	            
	            @Override
	            public void onPageScrollStateChanged(int arg0)
	            {
	                // TODO Auto-generated method stub
	                
	            }
	        });
	        mPagerAction = new Runnable()
	        {
	            @Override
	            public void run()
	            {
	                
	                if (mItem != 0)
	                {
	                    if (isFrist == true)
	                    {
	                        mCurrentItem = 0;
	                        isFrist = false;
	                    }
	                    else
	                    {
	                        if (mCurrentItem == items.size() - 1)
	                        {
	                            mCurrentItem = 0;
	                        }
	                        else
	                        {
	                            mCurrentItem++;
	                        }
	                    }
	                    
	                    pager.setCurrentItem(mCurrentItem);
	                    mGroup.check(radioButtonID[mCurrentItem]);
	                    
	                }
	                pager.postDelayed(mPagerAction, 2500);
	            }
	        };
	        pager.postDelayed(mPagerAction, 100);
		
	}
	
	 private void initAllItems()
	    {
	        // 初始化Viewpager的所有item
	        for (int i = 0; i < imgResIDs.length; i++)
	        {
	            items.add(initPagerItem(imgResIDs[i]));
	        }
	        mItem = items.size();
	    }
	    
	    private View initPagerItem(int resID)
	    {
	        View layout1 = getLayoutInflater().inflate(R.layout.tuijian_header, null);
	        ImageView imageView1 = (ImageView) layout1.findViewById(R.id.tuijian_header_img);
	        imageView1.setImageResource(resID);
	        return layout1;
	    }

	/**
	 * 获取指定类型的新闻列表
	 * 
	 * @param cid
	 *            类型ID
	 * @param newsList
	 *            保存新闻信息的集合
	 * @param startnid
	 *            分页
	 * @param firstTimes
	 *            是否第一次加载
	 */
	private int getSpeCateNews(int cid, List<HashMap<String, Object>> newsList,
			int startnid, Boolean firstTimes) {
		if (firstTimes) {
			// 如果是第一次，则清空集合里数据
			newsList.clear();
		}
		// 请求URL和字符串
		// 如果想在模拟器simulator上面访问你的电脑，可以使用android内置的IP 10.0.2.2, 10.0.2.2
		// 是模拟器设置的特定ip，是你的电脑的别名alias
		// 在模拟器上用10.0.2.2访问你的电脑本机
		// (也可以用电脑自己的IP地址)，不能使用localhost或127.0.0.1，那会让模拟器指向自己
//		String url = "http://192.168.137.1:8080/web/getSpecifyCategoryNews";
		String params = "startnid=" + startnid + "&count=" + NEWSCOUNT
				+ "&cid=" + cid;
		// System.out.println("url:"+url+"?"+params);
		SyncHttp syncHttp = new SyncHttp();
		try {
			// 以Get方式请求，并获得返回结果
			String retStr = syncHttp.httpGet(URL.main_url, params);
			JSONObject jsonObject = new JSONObject(retStr);

			// 获取返回码，0表示成功
			int retCode = jsonObject.getInt("ret");

			if (0 == retCode) {
				JSONObject dataObject = jsonObject.getJSONObject("data");
				// 获取返回数目
				int totalnum = dataObject.getInt("totalnum");
				if (totalnum > 0) {
					// 获取返回新闻集合
					JSONArray newslist = dataObject.getJSONArray("newslist");
					for (int i = 0; i < newslist.length(); i++) {
						JSONObject newsObject = (JSONObject) newslist.opt(i);
						HashMap<String, Object> hashMap = new HashMap<String, Object>();
						hashMap.put("nid", newsObject.getInt("nid"));
						hashMap.put("newslist_item_title",
								newsObject.getString("title"));
						hashMap.put("newslist_item_digest",
								newsObject.getString("digest"));
						hashMap.put("newslist_item_source",
								newsObject.getString("source"));
						hashMap.put("newslist_item_ptime",
								newsObject.getString("ptime"));
//						hashMap.put("newslist_item_comments",
//								newsObject.getString("commentcount"));
						newsList.add(hashMap);
//						mNewsListAdapter.notifyDataSetChanged();
						
					}
					return SUCCESS;
				} else {
					if (firstTimes) {
						return NONEWS;
					} else {
						return NOMORENEWS;
					}
				}
			} else {
				return LOADERROR;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return LOADERROR;
		}
	}

	private OnClickListener loadMoreListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
//			mNewsListAdapter.notifyDataSetChanged();
			loadNewsAsyncTask = new LoadNewsAsyncTask();
			switch (v.getId()) {
			case R.id.loadmore_btn:
				// 获取该栏目下新闻
				// getSpeCateNews(mCid,mNewsData,mNewsData.size(),false);
				// 通知进行更新
				//mNewsListAdapter.notifyDataSetChanged();
				loadNewsAsyncTask.execute(mCid, mNewsData.size(), false);
				break;
			case R.id.titlebar_refresh:
				loadNewsAsyncTask.execute(mCid, 0, true);
				break;
			}

		}
	};

	private class LoadNewsAsyncTask extends AsyncTask<Object, Integer, Integer> {

		@Override
		protected void onPreExecute() {
			mNewsListAdapter.notifyDataSetChanged();
			// 隐藏刷新按钮
			mTitlebarRefresh.setVisibility(View.GONE);
			// 显示进度条
			mLoadnewsProgress.setVisibility(View.VISIBLE);
			// 设置LoadMore Button 显示文本
			mLoadMoreBtn.setText(R.string.loadmore_txt);
		}

		@Override
		protected Integer doInBackground(Object... params) {
//			mNewsList.setAdapter(mNewsListAdapter);
			mNewsListAdapter.notifyDataSetChanged();
			return getSpeCateNews((Integer) params[0], mNewsData,
					(Integer) params[1], (Boolean) params[2]);
		}

		@Override
		protected void onPostExecute(Integer result) {
			// 根据返回值显示相关的Toast
			switch (result) {
			case NONEWS:// 该栏目下没有新闻
				Toast.makeText(MainActivity.this, R.string.no_news,
						Toast.LENGTH_SHORT).show();
				break;
			case NOMORENEWS:// 该栏目下没有更多新闻
				Toast.makeText(MainActivity.this, R.string.no_more_news,
						Toast.LENGTH_SHORT).show();
				break;
			case LOADERROR:// 加载失败
				Toast.makeText(MainActivity.this, R.string.load_news_failure,
						Toast.LENGTH_SHORT).show();
				break;
			}
			mNewsListAdapter.notifyDataSetChanged();
			// 显示刷新按钮
			mTitlebarRefresh.setVisibility(View.VISIBLE);
			// 隐藏进度条
			mLoadnewsProgress.setVisibility(View.GONE);
			// 设置LoadMore Button 显示文本
			mLoadMoreBtn.setText(R.string.loadmore_btn);
		}
	}
	
	/**
	 * 双击返回键退出应用
	 * */
	private long exitTime = 0;
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() - exitTime > 2000) {
//			String url="http://172.27.35.1:8080/web//DianzanServlet";
			FinalHttp fh = new FinalHttp();
			AjaxParams params = new AjaxParams();
			params.put("delete_id", "delete_id");
			params.put("updata", "updata");
			params.put("username", my.getUsername());
			fh.post(URL.login_url, params, new AjaxCallBack<Object>() {
				@Override
				public void onSuccess(Object t) {
					super.onSuccess(t);
				}
			});
			Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
			
			exitTime = System.currentTimeMillis();
			
		} else {
			my.setFlag(false);
			this.finish();
			
		}
		
		// super.onBackPressed();
	}
}